<!--
 * @description  : 证件-烟草专卖零售许可证行政许可卷内目录
 * @descriptionDetail: 证件-烟草专卖零售许可证行政许可卷内目录
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-07-15 15:29:13
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
    </theme-navbar>
    <!-- #endif -->
    <view class="content">
      <view>
        <u-swipe-action
          :show="item.show"
          :index="index"
          :options="options"
          :disabled="isDisabled"
          v-for="(item, index) in docList"
          :key="index"
          @click="swipeClick"
          @open="swipeOpen"
        >
          <view class="item u-border-bottom">
            <!-- 此层wrap在此为必写的，否则可能会出现标题定位错误 -->
            <view class="title-wrap">
              <u-row>
                <u-col span="12">
                  <view class="">
                    <!-- 《{{ item.docName }}》 -->
                    <u-input
                      :disabled="isDisabled"
                      placeholder=""
                      v-model="item.docName"
                      @blur="checkDocName('docName',item)"
                    />
                  </view>
                </u-col>
              </u-row>
              <u-row>
                <u-col span="4">
                  <view class="u-flex">
                    页数：
                    <u-input
                      :disabled="isDisabled"
                      type="number"
                      placeholder=""
                      v-model="item.pageNums"
                      @input="checkNumber('pageNums',item)"
                      @blur="checkNumberA('pageNums',item)"
                    />
                  </view>
                </u-col>
                <u-col span="4">
                  <view class="u-flex">
                    页次：{{ item.pageIndex }}
                  </view>
                </u-col>
                <u-col span="4">
                  <view class="u-flex">
                    材料：1份
                  </view>
                </u-col>
              </u-row>
            </view>
          </view>
        </u-swipe-action>
        <view class="footer">
          本卷连面带底共计：{{ basicInfo.totalPageNum }} 页次
        </view>
        <view class="remark">
          备注：
          <u-input
            type="textarea"
            :disabled="isDisabled"
            :border="true"
            border-color="#CED5E4"
            v-model="basicInfo.fileDirMemo"
          />
        </view>
      </view>

      <view class="query-btn">
        <u-button
          type="primary"
          class="u-btn u-m-l-25 u-m-r-25"
          v-if="!docIns.step || docIns.step == 'edit'"
          @click="submitAudit('save')"
        >
          保存
        </u-button>
        <u-button
          type="primary"
          class="u-btn"
          v-if="!docIns.step || docIns.step == 'edit'"
          @click="submitAudit('submit')"
        >
          提交
        </u-button>
        <u-button
          type="primary"
          class="u-btn  u-m-l-25"
          v-if="!!docIns.step && docIns.step != 'edit'"
          @click="downloadFile"
        >
          打印
        </u-button>
      </view>
    </view>
  </view>
</template>

<script>
import certificateService from "@/service/certificate/certificate.service.js";
import commonService from "@/service/common/common.service";
import {
  LOG_STATUS,LOG_OP_TYPE,
} from '@/service/common/mapping/enum.js';
export default {
  data() {
    return {
      preParams: {},
      docIns: {},
      docList: [],
      beginTime: "",
      isDisabled: false,
      show: false,
      basicInfo: {},
      options: [{
        text: '选择材料',
        style: {
          backgroundColor: '#007aff',
        },
      },
      {
        text: '删除',
        style: {
          backgroundColor: '#dd524d',
        },
      },
      ],
    };
  },
  computed: {
    docListA: function() {
      return JSON.parse(JSON.stringify(this.docList));
    },
  },
  watch: {
    docList(newValue) {
      let self = this;
      if (newValue) {
        newValue.forEach(item => {
          self.$set(item, 'show', false);
        });
      }
    },
    'docListA': {
      handler: function(newVal, oldVal) {
        let self = this;
        if (newVal.length != 0 && oldVal.length != 0) {
          let Nums = [];
          let sum = 0;
          for (let i = 0; i < newVal.length; i++) {
            sum += Number(newVal[i].pageNums);
            Nums[i] = sum;
          }
          for (let i = 0; i < newVal.length; i++) {
            if (newVal[i].pageNums != '' && newVal[i].pageNums != oldVal[i].pageNums) {
              for (let k = i; k < newVal.length; k++) {
                if (newVal[k].pageNums != 1) {
                  if (k - 1 < 0) {
                    self.$set(this.docList[k], 'pageIndex', `1-${Nums[k]}`);
                  } else {
                    self.$set(this.docList[k], 'pageIndex', `${Nums[k - 1] + 1}-${Nums[k]}`);
                  }

                } else {
                  self.$set(this.docList[k], 'pageIndex', `${Nums[k]}`);
                }
              }
              this.basicInfo.totalPageNum = Nums[newVal.length - 1] + 3;
            }
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  onLoad() {
    this.preParams = this.getRouteParam();
  },
  created() {
    commonService.getCurrentTime().then(res2 => {
      this.beginTime = res2.success ? res2.msg : this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss');
    });
    this.initData();
  },
  methods: {
    initData() {
      certificateService.getDocIns(this.preParams.docInsUuid).then((dr) => {
        this.docIns = dr.bean;
        this.isDisabled = this.docIns.step != 'edit';
      })
      certificateService.getDirMainId({
        id: this.preParams.docInsUuid,
        docUuid: this.preParams.docUuid,
        bizUuid: this.preParams.bizUuid,
      }).then(res => {
        if (res.success) {
          this.basicInfo = res.data[0];
          certificateService.licensDirectory({
            handleMainUuid: this.basicInfo.handleMainUuid,
            dirMstId: this.basicInfo.dirMstId,
          }).then(it => {
            if (it.success) {
              let Nums = [];
              let sum = 0;
              for (let i = 0; i < it.data.length; i++) {
                sum += Number(it.data[i].pageNums);
                Nums[i] = sum;
              }
              for (let i = 0; i < it.data.length; i++) {

                for (let k = i; k < it.data.length; k++) {
                  if (it.data[k].pageNums != 1) {
                    if (k - 1 < 0) {
                      this.$set(it.data[k], 'pageIndex', `1-${Nums[k]}`);
                    } else {
                      this.$set(it.data[k], 'pageIndex',
                        `${Nums[k - 1] + 1}-${Nums[k]}`);
                    }

                  } else {
                    this.$set(it.data[k], 'pageIndex', `${Nums[k]}`);
                  }
                }
                this.basicInfo.totalPageNum = Nums[it.data.length - 1] + 3;

              }
            }
            this.docList = it.data;
          })
        } else {
          this.$u.toast(res.msg);
        }
      })

    },
    // swipe点击事件
    swipeClick(index, index1) {
      if (index1 == 1) {
        this.docList.splice(index, 1);
        this.$u.toast(`删除了第${index}个文件`);
      } else {
        this.docList[index].show = false;
        this.setRouteParam({
          bizUuid: this.preParams.bizUuid,
          docInsUuid: this.docList[index].docInsUuid,
        });
        this.$u.route('pages/certificate/components/fileMaterial');
      }
    },
    // 如果打开一个的时候，不需要关闭其他，则无需实现本方法
    swipeOpen(index) {
      // 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
      // 原本为'false'，再次设置为'false'会无效
      this.docList[index].show = true;
      this.docList.map((val, idx) => {
        if (index != idx) this.docList[idx].show = false;
      })
    },
    // 页数输入框校验
    checkNumber(val, obj) {
      if (obj[val]) {
        if (Number(obj[val] <= 0)) {
          this.$u.toast("请输入大于0的整数");
          obj[val] = 1;
          return;
        }
        obj[val] = obj[val].replace(/\D|^0/g, '');
      }
    },
    checkNumberA(val, obj) {
      if (obj[val]) {
        this.checkNumber(val, obj);
      } else {
        obj[val] = 1;
      }
    },
    // 文件名不为空校验
    checkDocName(val, obj) {
      if (this.$u.test.isEmpty(obj[val])) {
        this.$u.toast("文件名不能为空");
      }
    },
    // 文书添加返回操作,文书添加操作未完成
    updateBackState(param) {
      if (param.backMaterial) {
        console.log(param.backMaterial);
      }
    },
    submitAudit(type) {
      let parm = {
        handleMainUuid: this.preParams.bizUuid,
        dirMstId: this.basicInfo.dirMstId,
        totalPageNum: this.basicInfo.totalPageNum,
        fileDirMemo: this.basicInfo.fileDirMemo,
        fileDirList: this.docList,
      }
      certificateService.saveDirdecoryDoc(parm, this.preParams.docUuid, this.preParams.docInsUuid, this
        .preParams.titemUuid, 'edit').then((dr) => {
        if (dr.success) {
          if (type === 'submit') {
            this.doSubmit(parm);
          } else {
            this.saveBehaviorLog(0, this.docIns);
            this.$u.toast("保存成功");
          }
        } else {
          this.$u.toast(res.msg);
        }
      })
    },
    doSubmit(parm) {
      certificateService.submitDirdecoryDoc(parm, this.preParams.docUuid, this.preParams.docInsUuid,
        this.preParams.titemUuid, this.docIns.step).then((res) => {
        if (res.success == true) {
          this.$u.toast("提交成功");
          certificateService.getDocIns(this.docIns.docInsUuid).then((doc) => {
            this.docIns = doc.bean;
            this.saveBehaviorLog(1, this.docIns);
            this.isDisabled = this.docIns.step != 'edit';
          })
          this.backPrev({
            paramKey: "athLicensDirectory",
            param: this.preParams,
          });
        } else {
          this.$u.toast(res.msg);
        }
      })
    },
    downloadFile() {
      if (!this.docIns.pdfFileId) {
        this.$u.toast("没有文书");
        return;
      }
      this.setRouteParam({
        fileId: this.docIns.pdfFileId,
      });
      this.$u.route('pages/commonPage/printerComponent');
    },
    /**
			 * @param {Boolean} status 提交还是保存
			 */
    saveBehaviorLog(status, doc) {
      commonService.getCurrentTime().then(res2 => {
        let param = {
          bizUuid: doc.bizUuid,
          docUuid: doc.docUuid,
          docInsUuid: doc.docInsUuid,
          bizType: LOG_STATUS.B007,
          operationType: status == 0 ? LOG_OP_TYPE.saveDoc : LOG_OP_TYPE.submitDoc,
          beginTime: this.beginTime,
          endTime: res2.success ? res2.msg : this.$u.timeFormat(Date.now(),
            'yyyy-mm-dd hh:MM:ss'),
          remark: doc.configIns.docName,
        };
        this.beginTime = param.endTime;
        commonService.saveBehaviorLog(param).then(res => {
          console.log(res);
        }).catch(e => {
          console.log(e);
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
	.item {
		display: flex;
		padding: 20rpx;
	}

	.title {
		text-align: left;
		font-size: 28rpx;
		color: $u-content-color;
		margin-top: 20rpx;
	}

	.footer {
		text-align: right;
	}

	.remark {
		margin-top: 50rpx;
	}

	.query-btn {
		display: flex;
		position: fixed;
		width: 95%;
		z-index: 999;
		bottom: var(--window-bottom, 0);

		.u-btn {
			width: 100%;
		}
	}
</style>
